﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SmartMeterParamFrame.Model.DIValueConverters
{
    /// <summary>
    /// 电量，与金额转换类
    /// 其格式如 xxxxxx.xx
    /// </summary>
    class Converter_MoneyAndEnergy : IDIDataConverter
    {
        private static uint MIN_ENERGY = uint.Parse("04000F01", System.Globalization.NumberStyles.AllowHexSpecifier);
        private static uint MAX_ENERGY = uint.Parse("04000FFF", System.Globalization.NumberStyles.AllowHexSpecifier);

        private static uint MIN_MONEY = uint.Parse("04001001", System.Globalization.NumberStyles.AllowHexSpecifier);
        private static uint MAX_MONEY = uint.Parse("040010FF", System.Globalization.NumberStyles.AllowHexSpecifier);

        public bool CanConverter(string di)
        {
            uint udi = uint.Parse(di, System.Globalization.NumberStyles.AllowHexSpecifier);

            if (udi >= MIN_ENERGY && udi <= MAX_ENERGY)
                return true;

            if (udi >= MIN_MONEY && udi <= MAX_MONEY)
                return true;

            return false;
        }

        public string ConvertToUI(string di, string value)
        {
            string[] vals = new string[2];
            string newValue = null;

            vals[0] = value.Substring(0, 6);
            vals[1] = value.Substring(6, 2);

            //处理 整数
            int firstPositiveIndex = vals[0].IndexOfAny(DIValueConverter.NUMBER_POSITIVE);
            vals[0] = vals[0].Substring(firstPositiveIndex, vals[0].Length - firstPositiveIndex);
            newValue += vals[0];
            newValue += ".";
            //处理小数
            int lastPositiveIndex = vals[1].LastIndexOfAny(DIValueConverter.NUMBER_POSITIVE);
            if (lastPositiveIndex >= 0)
            {
                newValue += vals[1].Substring(0, lastPositiveIndex + 1);
            }
            else
            {
                newValue += "0";
            }
            return newValue;
        }

        public string ConvertToLow(string di, string value)
        {
            string newValue = "";
            string[] ss = value.Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries);

            ss[0] = ss[0].PadLeft(6, '0');
            newValue = ss[0];
            if (ss.Length >= 2)
            {
                ss[1] = ss[1].PadRight(2, '0');
                newValue += ss[1];
            }
            else
            {
                newValue += "00";
            }
            return newValue;
        }

        public bool ValidateValue(string di, string value)
        {
            throw new NotImplementedException();
        }
    }
}
